import json
from datetime import datetime, timedelta

def load_data_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

def get_previous_trading_days(latest_date_str, num_days):
    latest_date = datetime.strptime(latest_date_str, "%Y%m%d")
    trading_days = [latest_date]

    while len(trading_days) < num_days + 1:
        latest_date -= timedelta(days=1)
        if latest_date.weekday() < 5:  # Monday to Friday are trading days
            trading_days.append(latest_date)

    trading_days.sort(reverse=True)
    return [date.strftime("%Y%m%d") for date in trading_days]

def find_recent_three_day_decline(data):
    stock_prices = {}
    all_dates = [day["trandt"] for day in data]
    latest_date = max(all_dates)

    # 获取最新日期往前推两天的交易日期（共三天）
    recent_dates = get_previous_trading_days(latest_date, 2)

    # 组织数据，以股票代码为键，存储每个日期的收盘价
    for day in data:
        date = day["trandt"]
        if date not in recent_dates:
            continue
        for stock in day["data"]["diff"]:
            stock_code = stock["f12"]
            close_price = stock["f2"]

            if stock_code not in stock_prices:
                stock_prices[stock_code] = {}

            stock_prices[stock_code][date] = close_price

    # 找出在最新三天内连续下跌的股票
    declining_stocks = []
    for stock_code, prices in stock_prices.items():
        if all(date in prices for date in recent_dates):
            if prices[recent_dates[0]] < prices[recent_dates[1]] < prices[recent_dates[2]]:
                declining_stocks.append({
                    "stock_code": stock_code,
                    "dates": recent_dates,
                    "prices": [prices[date] for date in recent_dates]
                })

    return declining_stocks

# 读取数据文件
file_path = 'D:\\PythonWorks\\pythonlearning\\01test\\tiantianjijin\\all_processed_data.json'
data = load_data_from_file(file_path)

# 查找最新连跌三天的股票
recent_three_day_declines = find_recent_three_day_decline(data)

# 输出结果
for decline in recent_three_day_declines:
    print(f"股票代码: {decline['stock_code']}")
    print(f"日期: {decline['dates']}")
    print(f"价格: {decline['prices']}")
    print()
